import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'package:labcloud_app/model/user/user_address_model.dart';
import 'package:labcloud_app/data/user_address.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';

class UserAddressPage extends StatefulWidget {
  const UserAddressPage({super.key});

  @override
  State<UserAddressPage> createState() => _UserAddressPageState();
}

class _UserAddressPageState extends State<UserAddressPage> {
  bool _isLoading = true;
  String _errorMessage = '';
  bool _isLoadAddressesCalled = false;

  Future<void> _loadAddresses(UserModel userModel, UserAddressModel addressModel) async {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      try {
        final client = GraphQLProvider.of(context).value;

        if (userModel.isLoggedIn) {
          await addressModel.loadUserAddresses(client);
        }

        if (mounted) {
          setState(() {
            _isLoading = false;
            _errorMessage = '';
          });
        }
      } catch (e) {
        if (mounted) {
          setState(() {
            _isLoading = false;
            _errorMessage = '加载地址列表失败: $e';
          });
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer2<UserModel, UserAddressModel>(
      builder: (context, userModel, addressModel, child) {
        // 当用户模型初始化完成且还未调用加载地址时，执行加载操作
        if (userModel.isLoggedIn && !_isLoadAddressesCalled) {
          _isLoadAddressesCalled = true;
          _loadAddresses(userModel, addressModel);
        }

        return Scaffold(
          appBar: AppBar(
            title: const Text('收货地址'),
          ),
          body: _buildAddressContent(userModel, addressModel),
          floatingActionButton: FloatingActionButton(
            onPressed: () async {
              final result = await Navigator.pushNamed(context, '/add_address');
              if (result != null && mounted) {
                // 如果从新增地址页面返回了结果，重新加载地址列表
                setState(() {
                  _isLoading = true;
                  _errorMessage = '';
                  _isLoadAddressesCalled = false;
                });
                _loadAddresses(userModel, addressModel);
              }
            },
            child: const Icon(Icons.add),
          ),
        );
      },
    );
  }

  Widget _buildAddressContent(UserModel userModel, UserAddressModel addressModel) {
    // 检查页面或模型是否在加载状态
    if (_isLoading || addressModel.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    // 检查页面是否有错误信息
    if (_errorMessage.isNotEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_errorMessage),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isLoading = true;
                  _errorMessage = '';
                  _isLoadAddressesCalled = false;
                });
                _loadAddresses(userModel, addressModel);
              },
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    // 检查模型是否有错误信息
    if (addressModel.errorMessage.isNotEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(addressModel.errorMessage),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isLoading = true;
                  _errorMessage = '';
                  _isLoadAddressesCalled = false;
                });
                _loadAddresses(userModel, addressModel);
              },
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    final addresses = addressModel.addresses;

    if (addresses.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.location_on,
              size: 80,
              color: Colors.grey,
            ),
            const SizedBox(height: 20),
            const Text(
              '暂无收货地址',
              style: TextStyle(
                fontSize: 18,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 30),
            ElevatedButton(
              onPressed: () async {
                final result = await Navigator.pushNamed(context, '/add_address');
                if (result != null && mounted) {
                  // 如果从新增地址页面返回了结果，重新加载地址列表
                  setState(() {
                    _isLoading = true;
                    _errorMessage = '';
                    _isLoadAddressesCalled = false;
                  });
                  _loadAddresses(userModel, addressModel);
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
              ),
              child: const Text('添加新地址'),
            ),
          ],
        ),
      );
    }

    return Column(
      children: [
        Expanded(
          child: RefreshIndicator(
            onRefresh: () async {
              setState(() {
                _isLoading = true;
                _errorMessage = '';
                _isLoadAddressesCalled = false;
              });
              await _loadAddresses(userModel, addressModel);
            },
            child: ListView.builder(
              itemCount: addresses.length,
              itemBuilder: (context, index) {
                final address = addresses[index];
                return _buildAddressItem(address);
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildAddressItem(UserAddress address) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  address.tag ?? '',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                if (address.isDefaultAddress)
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.blue,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: const Text(
                      '默认',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              address.recipientName ?? '',
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              address.phone ?? '',
              style: const TextStyle(
                fontSize: 14,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              address.fullAddress,
              style: const TextStyle(
                fontSize: 14,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                TextButton(
                  onPressed: () {
                    // TODO: 编辑地址
                    _editAddress(context, address);
                  },
                  child: const Text('编辑'),
                ),
                TextButton(
                  onPressed: () {
                    // 删除地址
                    _deleteAddress(context, address);
                  },
                  child: const Text('删除'),
                ),
                if (!address.isDefaultAddress)
                  TextButton(
                    onPressed: () {
                      // TODO: 设为默认地址
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('设为默认地址功能待实现')),
                      );
                    },
                    child: const Text('设为默认'),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 编辑地址
  void _editAddress(BuildContext context, UserAddress address) async {
    // 显示一个提示，告知用户编辑功能正在开发中
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('编辑地址功能正在开发中')),
    );
    
    // TODO: 实现编辑地址功能
    // 可以通过导航到编辑地址页面并传递地址参数来实现
    // Navigator.pushNamed(context, '/edit_address', arguments: address);
  }

  // 删除地址
  void _deleteAddress(BuildContext context, UserAddress address) async {
    final bool confirm = await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: const Text('确认删除'),
              content: const Text('确定要删除这个收货地址吗？'),
              actions: <Widget>[
                TextButton(
                  child: const Text('取消'),
                  onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                ),
                TextButton(
                  child: const Text('确定'),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
              ],
            );
          },
        ) ??
        false;

    if (confirm) {
      try {
        final userModel = Provider.of<UserModel>(context, listen: false);
        final addressModel = Provider.of<UserAddressModel>(context, listen: false);
        final client = GraphQLProvider.of(context).value;

        if (!userModel.isLoggedIn) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('用户未登录')),
            );
          }
          return;
        }

        // 使用GraphQL删除地址
        final result = await client.mutate(
          MutationOptions(
            document: gql(UserGQL.fetchDeleteUserAddress),
            variables: {
              'addressId': address.id != null ? int.parse(address.id.toString()) : null,
            },
          ),
        );

        if (result.hasException) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('删除地址失败: ${result.exception.toString()}')),
            );
          }
        } else {
          // 重新加载地址列表
          await addressModel.loadUserAddresses(client);
          
          // 触发页面重建以更新UI
          if (mounted) {
            setState(() {
              // 重新设置状态以触发重建
            });
            
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('地址删除成功')),
            );
          }
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('删除地址失败: $e')),
          );
        }
      }
    }
  }
}